<template>
  <v-container>
    <div class="d-flex justify-space-between align-center mb-6">
      <h1 class="text-h4">我的训练模板</h1>
      <v-btn color="primary" to="/template-editor/new" prepend-icon="mdi-plus">
        创建新模板
      </v-btn>
    </div>

    <v-chip-group
        v-model="activeTag"
        selected-class="text-primary"
        column
        class="mb-6"
    >
      <v-chip
          v-for="tag in tagOptions"
          :key="tag"
          :value="tag"
          filter
          variant="outlined"
      >
        {{ tag }}
      </v-chip>
    </v-chip-group>

    <div v-if="loading" class="text-center pa-10">
      <v-progress-circular indeterminate color="primary" size="64"></v-progress-circular>
    </div>

    <v-alert type="info" v-else-if="filteredTemplates.length === 0" variant="tonal">
      <p v-if="templates.length === 0">你还没有创建任何训练模板。点击右上角的“创建新模板”来设计你的第一个训练计划吧！</p>
      <p v-else>没有找到符合筛选条件的模板。</p>
    </v-alert>

    <v-row v-else>
      <v-col v-for="template in filteredTemplates" :key="template.id" cols="12" md="4" sm="6">

        <v-card class="d-flex flex-column" height="100%">

          <v-card-title class="d-flex justify-space-between align-center">
            <span class="font-weight-bold">{{ template.name }}</span>
            <div>
              <v-btn icon="mdi-eye-outline" variant="text" size="small" color="grey" disabled></v-btn>
              <v-btn icon="mdi-share-variant-outline" variant="text" size="small" color="grey" disabled></v-btn>
            </div>
          </v-card-title>

          <v-card-text>
            <v-list density="compact" bg-color="transparent">
              <v-list-item prepend-icon="mdi-run" class="px-0">
                动作数: {{ template.exerciseCount }} 个
              </v-list-item>

              <v-list-item prepend-icon="mdi-target" class="px-0">
                目标: {{ formatGoal(template.goal) }}
              </v-list-item>

              <v-list-item prepend-icon="mdi-chart-line" class="px-0">
                难度: {{ formatDifficulty(template.avgDifficulty) }}
              </v-list-item>

              <v-list-item prepend-icon="mdi-tag-outline" class="px-0">
                标签: {{ formatTags(template.tags) }}
              </v-list-item>
            </v-list>
          </v-card-text>

          <v-spacer></v-spacer>

          <div class="text-caption text-medium-emphasis px-4 pt-2">
            🕒 上次使用: {{ template.lastUsedDate ? template.lastUsedDate : '暂无' }}
          </div>

          <v-card-actions>
            <v-btn
                variant="text"
                color="grey"
                :to="`/template-editor/${template.id}`"
            >
              编辑
            </v-btn>

            <v-btn icon="mdi-delete" variant="text" color="grey" size="small" @click="confirmDeleteTemplate(template)"></v-btn>

            <v-spacer></v-spacer>

            <v-btn
                color="primary"
                variant="flat"
                @click="openStartTrainingDialog(template)"
            >
              使用
            </v-btn>
          </v-card-actions>
        </v-card>
      </v-col>
    </v-row>

    <v-dialog v-model="startDialog.show" max-width="500px" persistent>
      <v-card :loading="startDialog.isLoading">
        <v-card-title>如何使用 "{{ startDialog.templateName }}"？</v-card-title>
        <v-card-text>
          选择一个你喜欢的方式来开始这个训练模板。
        </v-card-text>
        <v-divider></v-divider>
        <v-list lines="two">
          <v-list-item
              prepend-icon="mdi-calendar-arrow-right"
              title="应用到下周"
              subtitle="将这个模板设置为你的下一个周常计划"
              @click="handleApplyToNextWeek"
              :disabled="startDialog.isLoading"
          ></v-list-item>
          <v-list-item
              prepend-icon="mdi-play-speed"
              title="立即开始训练"
              subtitle="创建一个临时的、从今天开始的训练"
              @click="handleStartImmediately"
              :disabled="startDialog.isLoading"
          ></v-list-item>
        </v-list>
        <v-card-actions>
          <v-spacer></v-spacer>
          <v-btn variant="text" @click="startDialog.show = false" :disabled="startDialog.isLoading">取消</v-btn>
        </v-card-actions>
      </v-card>
    </v-dialog>

  </v-container>
</template>

<script setup>
import { ref, onMounted, reactive, computed } from 'vue';
import { useRouter } from 'vue-router';
import Request from '@/utils/Request';
import { useNotificationStore } from '@/stores/notification';

const loading = ref(true);
const templates = ref([]); // <-- 将存储 C# 返回的【所有】模板
const router = useRouter();
const notificationStore = useNotificationStore();

// --- 【!! V4 新增：筛选状态 !!】 ---
const activeTag = ref('全部'); // 默认选中的标签
const tagOptions = ['全部', '居家', '健身房', '减脂', '增肌', '保持']; // 筛选器选项

// --- (对话框状态保持不变) ---
const startDialog = reactive({
  show: false,
  templateId: null,
  templateName: '',
  isLoading: false,
});

// --- 【!! V4 升级：筛选逻辑 !!】 ---
// (使用计算属性在前端执行筛选)
const filteredTemplates = computed(() => {
  const tag = activeTag.value;
  if (tag === '全部') {
    return templates.value;
  }

  return templates.value.filter(t => {
    // 检查 C# 计算返回的 "Goal" (目标)
    if (tag === '减脂' && t.goal === 0) return true; // HealthGoal.FatLoss = 0
    if (tag === '增肌' && t.goal === 1) return true; // HealthGoal.MuscleGain = 1
    if (tag === '保持' && t.goal === 2) return true; // HealthGoal.Maintain = 2

    // 检查 C# 计算返回的 "Tags" (标签)
    if (t.tags && t.tags.includes(tag)) return true; // "居家" or "健身房"

    return false;
  });
});

// --- (API 调用保持不变) ---
const fetchMyTemplates = () => {
  loading.value = true;
  Request.get('/workout-templates/my')
      .then(response => {
        templates.value = response.data;
      })
      .catch(error => {
        console.error("获取我的模板失败:", error);
      })
      .finally(() => {
        loading.value = false;
      });
};

onMounted(fetchMyTemplates);

// --- (删除逻辑保持不变) ---
const confirmDeleteTemplate = (template) => {
  if (window.confirm(`确定要删除模板 "${template.name}" 吗？此操作不可撤销。`)) {
    deleteTemplate(template.id);
  }
};
const deleteTemplate = (templateId) => {
  Request.delete(`/workout-templates/${templateId}`)
      .then(() => {
        templates.value = templates.value.filter(t => t.id !== templateId);
        notificationStore.success('模板已成功删除');
      })
      .catch(error => {
        console.error("删除模板失败:", error);
      });
};


const formatGoal = (goal) => {
  const map = { 0: '减脂', 1: '增肌', 2: '保持' };
  return map[goal] ?? '未设定';
};

const formatDifficulty = (diff) => {
  const map = { 0: '初级', 1: '中级', 2: '高级', 3: '零基础' };
  return map[diff] ?? 'N/A';
};

const formatTags = (tags) => {
  if (!tags || tags.length === 0) return '无';
  return tags.join(', ');
};

// --- (对话框逻辑保持不变) ---
const openStartTrainingDialog = (template) => {
  startDialog.templateId = template.id;
  startDialog.templateName = template.name;
  startDialog.isLoading = false;
  startDialog.show = true;
};
const handleApplyToNextWeek = () => {
  startDialog.isLoading = true;
  Request.post(`/workouts/plan/apply-template-for-next-week/${startDialog.templateId}`)
      .then(() => {
        notificationStore.success(`已成功将模板 "${startDialog.templateName}" 应用为下周计划！`);
        startDialog.show = false;
      })
      .catch(error => {
        console.error("应用到下周失败:", error);
      })
      .finally(() => {
        startDialog.isLoading = false;
      });
};
const handleStartImmediately = () => {
  startDialog.isLoading = true;
  Request.post(`/workouts/plan/apply-template-for-current-week/${startDialog.templateId}`)
      .then(() => {
        notificationStore.success("本周计划已更新！正在刷新页面...");
        startDialog.show = false;
        if (router.currentRoute.value.name === 'Workouts') {
          window.location.reload();
        } else {
          router.push({ name: 'Workouts' });
        }
      })
      .catch(error => {
        console.error("立即开始训练失败:", error);
      })
      .finally(() => {
        startDialog.isLoading = false;
      });
};
</script>